<template>
    <view class="container">
        <!-- 顶部固定区域 -->
        <view class="fixed-content">
            <!-- 顶部用户信息区域 -->
            <view class="user-info-box">
                <view class="user-avatar-section">
                    <image class="avatar" :src="userStore.userNextInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" @click="handleAuthClick"></image>
                    <text class="text-primary">{{userStore.userNextInfo.name}}</text>
                </view>
                <view class="auth-box">
                    <text class="text-secondary">亲情授权</text>
                    <uni-icons type="right" size="16" color="#999"></uni-icons>
                </view>
            </view>

            <!-- 功能按钮区域 -->
            <view class="function-box">
                <view class="function-item" v-for="(item, index) in functionList" :key="index" @click="handleFunctionClick(item)">
                    <view class="function-icon">
                        <uni-icons :type="item.icon" size="24" color="#2ac2d1"></uni-icons>
                    </view>
                    <text class="text-primary">{{ item.text }}</text>
                </view>
            </view>
        </view>

        <!-- 可滚动的内容区域 -->
        <scroll-view
            class="scrollable-content"
            scroll-y
            refresher-enabled
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh"
            @scrolltolower="handleScrollToLower"
            :lower-threshold="100"
        >
            <!-- 药品列表区域 -->
            <view class="medicine-list">
                <uni-swipe-action>
                    <uni-swipe-action-item
                        v-for="(item, index) in medicineList"
                        :key="index"
                        :right-options="swipeOptions"
                        @click="handleSwipeClick($event, index, item.id)"
                    >
                        <view class="medicine-item">
                            <view class="medicine-info">
                                <image class="medicine-image" :src="item.picture" mode="aspectFit"></image>
                                <view class="medicine-name">{{ item.drugName }}</view>
                            </view>
                            <view class="medicine-actions">
                                <button class="action-btn" size="mini" plain @click="handleAddToGroup(item.id, item.drugName)">添加到药品组合</button>
                                <button class="action-btn" size="mini" plain @click="handleDetail(item.id)">详情</button>
                            </view>
                        </view>
                    </uni-swipe-action-item>
                </uni-swipe-action>

                <!-- 加载更多提示 -->
                <view class="loading-more" v-if="hasMore">
                    <view class="loading-text" v-if="isLoading">正在加载更多...</view>
                    <view class="loading-text" v-else></view>
                </view>
                <view class="no-more" v-else>
                    <view class="no-more-text">没有更多数据了</view>
                </view>
            </view>
        </scroll-view>

        <!-- 右下角添加按钮 -->
        <view class="float-icon" @click="navigateToEdit">
            <uni-icons type="plusempty" size="24" color="#2ac2d1"></uni-icons>
            <view class="add-count" v-if="addedMedicineCount > 0">{{ addedMedicineCount }}</view>
        </view>
    </view>
</template>

<script>
import { ref } from 'vue';
import { useMedicineStore } from '@/store/medicine';
import navigator from '@/utils/navigator';
import { useUserStore } from '../../store/user';

export default {
    setup() {
        const medicineStore = useMedicineStore();
        const medicineList = ref([]); // 使用 ref 创建响应式数据
        const userStore = useUserStore()
        const fetchData = async (page) => {
            await medicineStore.getMedicineList(page); // 获取药品数据
            medicineList.value = medicineStore.medicines; // 将 medicineStore.medicines 赋值给 medicineList
            console.log('Medicine list updated:', medicineList.value);
        };

        return {
            medicineStore,
            medicineList, // 返回 medicineList
            fetchData,
            userStore
        };
    },
    onLoad() {
      console.log(1);
        this.fetchData(1); // 页面加载时调用 fetchData
        setTimeout(() => {
            this.total = this.medicineStore.total;
        }, 1000);
    },
    data() {
        return {
            addedMedicineCount: 0,
            addedMedicines: [],
            functionList: [
                { icon: 'list', text: '药品列表', path: '' },
                { icon: 'star', text: '药品组合', path: '/pages/group/group' },
                { icon: 'notification', text: '用药提醒', path: '/pages/reminder/reminder' },
            ],
            page: 1,
            pageSize: 5,
            total: 0,
            hasMore: true,
            isLoading: false,
            isRefreshing: false,
            swipeOptions: [
                {
                    text: '删除',
                    style: {
                        backgroundColor: '#dd524d', // 删除按钮的背景颜色
                    },
                },
            ],
        };
    },
    methods: {
        handleFunctionClick(item) {
            if (item.path) {
                navigator.navigate(item.path);
            }
        },
        handleAuthClick() {
            navigator.navigate('/pages/auth/auth');
        },
        handleSwipeClick(e, index, id) {
            if (e.content.text === '删除') {
                this.handleDelete(index,id); // 调用删除方法
            }
        },
        handleDelete(index,id) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这个药品吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.medicineList.splice(index, 1); // 从列表中删除该项
                        this.medicineStore.deleteMedicine(id)
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success',
                        });
                    }
                },
            });
        },
        handleDetail(id) {
            navigator.navigate('/pages/detail/detail', {
                id,
            });
        },
        async onRefresh() {
            console.log('触发下拉刷新');
            this.isRefreshing = true;
            this.page = 1;
            this.hasMore = true;
            try {
                await this.fetchData(1); // 重新加载数据
                uni.showToast({
                    title: '刷新成功',
                    icon: 'success',
                });
            } catch (error) {
                uni.showToast({
                    title: '刷新失败',
                    icon: 'error',
                });
            } finally {
                this.isRefreshing = false;
            }
        },
        handleScrollToLower() {
            if (this.page * this.pageSize >= this.total) {
                this.hasMore = false;
                return;
            }
            this.page++;
            this.fetchData(this.page);
        },
        handleAddToGroup(id, name) {
            const isAlreadyAdded = this.addedMedicines.some(item => item.id === id);
            if (!isAlreadyAdded) {
                this.addedMedicines.push({ id, name }); // 将药品 id 和 name 添加到数组中
                this.addedMedicineCount++; // 增加计数
                uni.showToast({
                    title: '已添加到组合',
                    icon: 'success',
                });
            } else {
                uni.showToast({
                    title: '该药品已添加',
                    icon: 'none',
                });
            }
        },
        navigateToEdit() {
			// 检查 addedMedicines 数组的长度
			if (this.addedMedicines.length < 2) {
				// 如果数组长度小于 2，显示提示框
				uni.showToast({
					title: '药品数量少于两个',
					icon: 'none'
				});
				return; // 阻止后续代码执行，不进行跳转
			}

			// 如果数组长度大于等于 2，执行跳转操作
			uni.navigateTo({
				url: '/pages/group/edit?addedMedicines=' + encodeURIComponent(JSON.stringify(this.addedMedicines)),
			});
			this.addedMedicineCount = 0;
			this.addedMedicines = []; // 清空数组
		}
    },
};
</script>

<style lang="scss">
.container {
	height: 100vh;
	background-color: #f5f5f5;
	position: relative;
	display: flex;
	flex-direction: column;
}

.fixed-content {
	background-color: #ffffff;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.user-info-box {
	padding: 30rpx 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	
	.user-avatar-section {
		display: flex;
		align-items: center;
		
		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background-color: #f0f0f0;
			margin-right: 20rpx;
		}
	}
	
	.auth-box {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background-color: #f8f8f8;
		border-radius: 30rpx;
	}
}

.function-box {
	padding: 30rpx 20rpx;
	display: flex;
	justify-content: space-around;
	
	.function-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.function-icon {
			width: 80rpx;
			height: 80rpx;
			background-color: rgba(42, 194, 209, 0.1);
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10rpx;
		}
	}
}

.scrollable-content {
	flex: 1;
	height: 0;
	padding-bottom: 20rpx;
}

.medicine-list {
	padding: 20rpx 20rpx 0;
	
	.medicine-item {
		background-color: #ffffff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-radius: 12rpx;
		
		.medicine-info {
			display: flex;
			align-items: center;
			
			.medicine-image {
				width: 80rpx;
				height: 80rpx;
				margin-right: 20rpx;
			}
			
			.medicine-name {
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.medicine-actions {
			display: flex;
			gap: 10rpx;
			
			.action-btn {
				font-size: 24rpx;
				color: #2ac2d1;
				border-color: #2ac2d1;
				
				&::after {
					border-color: #2ac2d1;
				}
			}
		}
	}
	
	.loading-more, .no-more {
		text-align: center;
		padding: 10rpx 0;
		
		.loading-text, .no-more-text {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.no-more {
		.no-more-text {
			color: #ccc;
		}
	}
}

.float-icon {
	position: fixed;
	right: 30rpx;
	bottom: 40rpx;
	width: 80rpx;
	height: 80rpx;
	background-color: #ffffff;
	border-radius: 50%;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 100;
}

.float-icon {
	position: fixed;
	right: 30rpx;
	bottom: 40rpx;
	width: 80rpx;
	height: 80rpx;
	background-color: #ffffff;
	border-radius: 50%;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 100;
	
	.add-count {
		position: absolute;
		top: 0;
		right: 0;
		background-color: #93e0e7;
		color: #ffffff;
		font-size: 20rpx;
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>